<?php
namespace app\api\controller;
use app\api\model\User;
use app\common\model\user\BalanceLog;
use think\Db;
use org\RabbitMQ;
/**
 * 清理未返完的订单
 * Class Settlement
 * @package app\api\controller
 */
class Settlement extends \think\Controller
{


    protected function log($pre,$data = null)
    {
        if($data) {
            $data = is_array($data) ? json_encode($data) : $data;
            file_put_contents("order-".date('Ymd', time()).".log",  $pre . $data .  "\n", FILE_APPEND);
        } else {
            file_put_contents("order-".date('Ymd', time()).".log",  $pre .  "\n", FILE_APPEND);
        }

    }

    /**
     *  获取设置信息
     * @param $wxappId
     * @return array|bool|false|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSetting(){
      
      
        $time=time();
      
        $this->log('1 接口入参: 当前时间',$time);
        $setList=collection(db('wxapp_setting')->where('end_time','<',$time)->select())->toArray();
        $rem=new RabbitMQ();
        $data=['list'=>$setList];
        $this->log('1 接口入参: ',$data);
        $rem->send($data,'userRefundListData','userRefundListDataLog','userRefundListDataLog');
    }

    /**
     * 将到期后用户未返回的余额转化成零钱返还给用户队列
     */
    public function getUsersBackAbonus(){
        $rmq = new RabbitMQ;
        $processMessage = function ($envelope, $queue) {
            $msg = $envelope->getBody();
            $params= json_decode($msg,true);
            foreach ($params as $key=>$value){
             $this->setUsersBackAccount($value['wxapp_id'],$value['periods_num']);
            }
        };
        $rmq->run($processMessage, 'userRefundListData','userRefundListDataLog','userRefundListDataLog');
    }

    /**
     *  将到期后用户未返回的余额转化成零钱返还给用户
     * @param $periodsNum
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function setUsersBackAccount($wxappId,$periodsNum){
      $userList=collection(db('divide_receives')->where(['type'=>0,'wxapp_id'=>$wxappId,'periods_num'=>$periodsNum])->order('create_time asc')->select())->toArray();
      foreach ($userList as $key=>$value){
         $this->setUserBlance($value['balance'],$value);
         $this->setUserUpdata($value['receives_id']);
      }

    }


    /**
     *  修改主表数据
     * @param $receivesId
     * @return int|string
     */
    private function setUserUpdata($receivesId){
        return db('divide_receives')->where('receives_id',$receivesId)->setField(['balance'=>0,'type'=>1]);
    }
    /**
     * 将用户多余的积分给用户加上
     * @param $chage  int 零钱
     * @param $item  int  订单
     * @throws \think\Exception
     */
    private function setUserBlance($chage,$item){
        $userModel=new User();
        $res=$userModel->where('user_id',$item['user_id'])->setInc('balance',$chage);
        if($res){
            // 用户余额变动明细
            BalanceLog::add(50, [
                'user_id'  =>$item['user_id'],
                'money'    =>+$chage,
                'wxapp_id' =>$item['wxapp_id'],
            ], ['order_no' =>$item['order_no']]);
        }
        return $res;

    }

}